package cn.xny.txcc.exception;



import cn.xny.txcc.code.ErrorCode;
import cn.xny.txcc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

//系统发生异常的时候-拦截请求
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 根据异常类型,定位执行哪个方法
    @ExceptionHandler(value = {Exception.class})
    public JSONResult  GlobalException(Exception ex){

        ex.printStackTrace();

        return JSONResult.error(ErrorCode.SYSTEM_ERROR);


    }

    @ExceptionHandler(value = {BusinessException.class})
    public JSONResult  GlobalException(BusinessException ex){
            String message = ex.getMessage();
        return JSONResult.error(message,"-2000");


    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public JSONResult  GlobalException(MethodArgumentNotValidException ex){

        StringBuffer sb = new StringBuffer();

        //ex.getBindingResult().getAllErrors().get(0).defaultMessage
        List<ObjectError> list = ex.getBindingResult().getAllErrors();
        list.forEach(er->{
            sb.append(er.getDefaultMessage()).append(",");

        });
        /*
            自己定义的业务异常
         */
        return JSONResult.error(sb.toString(),"-2001");
    }










}
